from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from django.conf import settings
from . import constants
from itsdangerous import BadData
import random


def encryopenid(openid):
    s = Serializer(secret_key=settings.secret_key, expires_in=constants.ACCESS_TOKEN_EXPIRES)  # 盐，过期时间
    obj = {"openid": openid}
    token = s.dumps(obj)  # 序列化得到一个btype类型的加密文字
    return token.decode()


def checkopenid(openid):
    s = Serializer(secret_key=settings.secret_key,expires_in=constants.ACCESS_TOKEN_EXPIRES)
    try:
        data = s.loads(openid)
    except BadData:
        return None
    else:
        return data.get("openid")
